<template>
<div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
        <el-row :gutter="20">
            <el-col :span="8">
                <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" >
                    <el-button slot="append" icon="el-icon-search" @click="selectUser"></el-button>
                </el-input>
            </el-col>
            <el-col :span="6"><el-button @click="dialogVisible = true" type="primary">添加用户</el-button></el-col>
            <!-- 添加用户 -->
            <el-dialog
            title="添加用户"
            @close="addFormClose"
            :visible.sync="dialogVisible"
            width="50%">
            <el-form :model="userForm" :rules="userFormRules" ref="userForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="userForm.password" show-password></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="userForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
            </el-dialog>

            <!-- 修改用户 -->
            <el-dialog
            title="修改用户"
            @close="editFormClose"
            :visible.sync="editVisible"
            width="50%">
            <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
            </el-dialog>
        </el-row>

        <!-- 用户数据 -->
        <el-table
        :data="users"
        :border="true"
        :stripe="true"
        style="width: 100%">
            <el-table-column
                type="index"
                >
                
            </el-table-column>
            <el-table-column
                prop="username"
                label="用户名"
                >
            </el-table-column>
            <el-table-column
                prop="mobile"
                label="手机号码"
                >
            </el-table-column>
            <el-table-column
                prop="email"
                label="邮箱"
                >
            </el-table-column>
            <el-table-column
                prop="role_name"
                label="角色"
                >
            </el-table-column>
            <el-table-column
                prop="mg_state"
                label="状态"
                >
                <template slot-scope="scope">
                    <el-switch
                    @change="changeStatus(scope.row)"
                    v-model="scope.row.mg_state"
                    active-color="#13ce66"
                    inactive-color="#ff4949">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                width="180px"
                >
                 <template slot-scope="scope">
                     <el-button @click="showEdit(scope.row)" size="mini" type="primary" icon="el-icon-edit"></el-button>
                     <el-button @click="deleteUser(scope.row.id)" size="mini" type="danger" icon="el-icon-delete"></el-button>
                     <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top">
                        <el-button @click="showRoleDialog(scope.row)" size="mini" type="warning" icon="el-icon-setting"></el-button>
                     </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[2,4,6,8]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>

            <!-- 分配角色 -->
            <el-dialog @close="clearRoleDialog" title="分配角色" :visible.sync="showRole" width="50%">
                <p><span>用户名:</span> {{userRole.username}}</p>
                <p><span>当前角色:</span> {{userRole.role_name}}</p>
                <el-select v-model="selectRole" placeholder="请选择角色">
                    <el-option v-for="role in roles" :key="role.id" :label="role.roleName" :value="role.id"></el-option>
                </el-select>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="showRole = false">取 消</el-button>
                    <el-button type="primary" @click="setRole">确 定</el-button>
                </span>
            </el-dialog>
    </el-card>
</div>
</template>

<script>
export default {
    data(){
        //自定义校验邮箱
        var checkEmail = (rule,value,cb) =>{
            const regEmail = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
            if(regEmail.test(value))return cb();
            cb(new Error("邮箱格式错误"));
        };
        //自定义校验电话号码
        var checkMobile = (rule,value,cb) =>{
            const regPhone = /^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$/;
            if(regPhone.test(value))return cb();
            cb(new Error("电话号码格式错误"));
        };
        return {
            users:[],
            queryInfo:{
                query:"",  
                pagenum:1,
                pagesize:4, 
            },
            total:0,
            dialogVisible:false,
            editVisible:false,
            showRole:false,
            selectRole:'',
            userForm:{
                username:'',
                password:'',
                email:'',
                mobile:'',
            },
            userFormRules:{
                username: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ],
            },
            editForm:{
                username:'',
                email:'',
                mobile:'',
                id:'',
            },
            editFormRules:{
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ],
            },
            userRole:{},
            roles:[],
            
        }
    },
    created(){
        this.getUsers();
    },
    methods:{
        //查询用户列表
        async getUsers(){
            const {data:res} = await this.$http.get("users",{params:this.queryInfo});
            if(res.meta.status !== 200)this.$message.error(this.meta.msg);
            this.users = res.data.users;
            this.total = res.data.total;
        },
        //分页事件
        handleSizeChange(newSize){
            this.queryInfo.pagesize = newSize;
            this.getUsers();
        },
        handleCurrentChange(newPage){
            this.queryInfo.pagenum = newPage;
            this.getUsers();
        },
        //修改用户状态事件
        async changeStatus(user){
            const {data:res} = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
            if(res.meta.status===200)this.$message.success(res.meta.msg);
            else {
                this.$message.error(res.meta.msg)
                user.mg_state = !user.mg_state;
            };
        },
        //搜索用户
        selectUser(){
             this.getUsers();
        },
        //添加用户
        addUser(){
            //校验表单
            this.$refs.userForm.validate(async val=>{
                if(val){
                    //发送请求增加用户
                    const{data:res} = await this.$http.post("users",this.userForm);
                    if(res.meta.status === 201){
                        this.$message.success("添加成功");
                        //关闭窗口
                        this.dialogVisible = false
                        //刷新用户列表
                        this.getUsers();
                    }else this.$message.error("添加失败");

                }
            });
        },
        //清空userForm
        addFormClose(){
             this.$refs.userForm.resetFields();
        },
        editFormClose(){
             this.$refs.editForm.resetFields();
        },
        //修改对话框
        showEdit(user){
            this.editForm.username = user.username;
            this.editForm.email = user.email;
            this.editForm.mobile = user.mobile;
            this.editForm.id = user.id;
            this.editVisible = true;
        },
         //修改用户
        editUser(){
            //校验表单
            this.$refs.editForm.validate(async val=>{
                if(val){
                    //发送请求增加用户
                    const{data:res} = await this.$http.put("users/"+this.editForm.id,{
                        email:this.editForm.email,
                        mobile:this.editForm.mobile
                    });
                    if(res.meta.status === 200){
                        this.$message.success(res.meta.msg);
                        //关闭窗口
                        this.editVisible = false
                        //刷新用户列表
                        this.getUsers();
                    }else this.$message.error(res.meta.msg);

                }
            });
        },
        //删除用户
        async deleteUser(id){
            await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                //确定删除
                const {data:res}=await this.$http.delete("users/"+id);
                if(res.meta.status===200){
                    this.$message.success(res.meta.msg);
                    this.getUsers();
                }else {
                    this.$message.error(res.meta.msg)
                }
            }).catch(() => {
                //取消删除
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        //设置角色
        async setRole(){
            if(!this.selectRole){
                return this.$message.error("请选则需要分配的角色");
            }
            const{data:res} = await this.$http.put("users/"+this.userRole.id+"/role",{
                id:this.userRole.id,
                rid:this.selectRole
            });
            if(res.meta.status!==200)return this.$message.error(res.meta.msg);
            this.$message.success(res.meta.msg);
            this.getUsers();
            this.showRole = false;
        },
        //打开角色面板
        async showRoleDialog(user){
            this.userRole = user;
            //查询所有角色
            const{data:res} = await this.$http.get("roles");
            if(res.meta.status!==200)this.$message.error(res.meta.msg);
            this.roles = res.data;
            this.showRole = true;
        },
        //清空选中角色
        clearRoleDialog(){
            this.selectRole = '';
            this.userRole = {};
        },

    }
}
</script>

<style lang="less" scoped>
    
</style>